package com.ilikesoup.instant;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;

public class ValidationUtils {

    private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    private ValidationUtils() {
    }

    public static <T> void validateParams(T object) {
        if (object == null) {
            throw new ValidationException("The parameters to be tested can not be null");
        }
        Set<ConstraintViolation<T>> violations = validator.validate(object);
        if (violations.isEmpty()) {
            return;
        }
        String errMsg = violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(System.lineSeparator()));
        throw new ValidationException(errMsg);
    }

}
